#ifndef __MY_FORMATTER_HPP__
#define __MY_FORMATTER_HPP__

#include "message.hpp"
#include <iostream>
#include <vector>
#include <memory>
#include <sstream>
#include <ctime>
#include <cassert>

namespace logs
{
    class FormatItem
    {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        virtual void format(std::ostream &out, const LogMsg &msg) = 0;
        virtual ~FormatItem() {}
    };

    class TimeFormatItem : public FormatItem
    {
    public:
        TimeFormatItem(const std::string &format = "%H:%M:%S")
            : _format(format)
        {
        }

        void format(std::ostream &out, const LogMsg &msg) override
        {
            time_t t = msg._ctime;
            struct tm *tm = localtime(&t);
            char buffer[32] = {0};
            strftime(buffer, 31, _format.c_str(), tm);
            out << buffer;
        }

    private:
        std::string _format;
    };

    class ThreadFormatItem : public FormatItem
    {
    public:
        ThreadFormatItem(const std::string &str = "") {}

        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._id;
        }
    };

    class NameFormatItem : public FormatItem
    {
    public:
        NameFormatItem(const std::string &str = "") {}

        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._name;
        };
    };

    class CFileFormatItem : public FormatItem
    {
    public:
        CFileFormatItem(const std::string &str = "") {}

        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._file;
        }
    };

    class CLineFormatItem : public FormatItem
    {
    public:
        CLineFormatItem(const std::string &str = "") {}

        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << std::to_string(msg._line);
        }
    };

    class LevelFormatItem : public FormatItem
    {
    public:
        LevelFormatItem(const std::string &str = "") {}

        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << LogLevel::tostring(msg._level);
        }
    };

    class MsgFormatItem : public FormatItem
    {
    public:
        MsgFormatItem(const std::string &str = "") {}

        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._payload;
        }
    };

    class TabFormatItem : public FormatItem
    {
    public:
        TabFormatItem(const std::string &str = "") {}

        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\t";
        }
    };

    class NLineFormatItem : public FormatItem
    {
    public:
        NLineFormatItem(const std::string &str = "") {}

        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\n";
        }
    };

    class OtherFormatItem : public FormatItem
    {
    public:
        OtherFormatItem(const std::string &str = "") : _str(str) {}

        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << _str;
        }

    private:
        std::string _str;
    };

    /*
        日志格式化类
        实现一个日志格式化类，两个成员变量：
            _pattern：记录格式化字符串
            _items：一个存储格式化解析项的数组，后续就是通过遍历这个数组将组织合法消息日志

        实现功能：
        公有接口：
            1.构造函数，内部调用解析函数parsePattern解析格式化字符串，获得解析项数组
            2.格式化输出函数format，主要函数，就是传入日志消息，根据构造函数时传入的格式化字符串组成返回合法日志消息字符串
        私有接口：
            1.解析函数parsePattern，解析格式化字符串，内部最后调用createItem获得解析项数组
            2.获得解析项createItem，通过key,val值判断最后返回特定解析项（这里就是真正new出来解析项的地方）
    */
    class Formatter
    {
    public:
        using ptr = std::shared_ptr<Formatter>;

        Formatter(const std::string &pattern = "[%d{%H:%M:%S}][%t][%p][%c][%f:%l] %m%n")
            : _pattern(pattern)
        {
            assert(parsePattern());
        }

        const std::string pattern() { return _pattern; }

        /*格式化输出*/
        std::string format(const LogMsg &msg)
        {
            std::stringstream ss;
            format(ss, msg);
            return ss.str();
        }
        std::ostream &format(std::ostream &out, const LogMsg &msg)
        {
            for (auto &iter : _items)
            {
                if (iter.get() != nullptr)
                    iter->format(out, msg);
            }
            return out;
        }

    private:
        /*解析格式化字符串，得到格式化句柄集合*/
        //"[%%d{%H:%M:%S}][%t][%p][%c][%f:%l] %m%n"
        bool parsePattern()
        {
            std::string key, val;
            std::vector<std::pair<std::string, std::string>> array;
            size_t pos = 0;
            size_t size = _pattern.size();
            while (pos < size)
            {
                if (_pattern[pos] != '%')
                {
                    val += _pattern[pos++];
                    continue;
                }
                if (pos + 1 < size && _pattern[pos + 1] == '%')
                {
                    val += '%';
                    pos += 2;
                    continue;
                }
                if (val.empty() == false)
                {
                    array.push_back(std::make_pair(key, val));
                    val.clear();
                }

                // 走到这里遇到了合适的格式化字符
                pos += 1; // 跳过当前%
                if (pos < size && isalpha(_pattern[pos]))
                {
                    key = _pattern[pos]; // 保存当前格式化字符
                }
                else
                {
                    std::cout << &_pattern[pos - 1] << "位置附近格式错误\n";
                    return false;
                }

                pos += 1; // 判断下一个字符是否是'{'
                bool err_format = false;
                if (pos < size && _pattern[pos] == '{')
                {
                    pos += 1;
                    err_format = true;
                    while (pos < size)
                    {
                        if (_pattern[pos] == '}')
                        {
                            err_format = false;
                            pos += 1;
                            break;
                        }
                        val += _pattern[pos++];
                    }
                }
                if (err_format == true)
                {
                    std::cout << "{}对应位置出错\n";
                    return false;
                }

                // 将合法结果导入
                array.push_back(std::make_pair(key, val));
                key.clear();
                val.clear();
            }

            for (auto &iter : array)
            {
                _items.push_back(createItem(iter.first, iter.second));
            }

            return true;
        }

        /*创建日志格式句柄*/
        FormatItem::ptr createItem(const std::string &key, const std::string &value)
        {
            if (key == "d")
                return std::make_shared<TimeFormatItem>(value);
            if (key == "t")
                return std::make_shared<ThreadFormatItem>();
            if (key == "p")
                return std::make_shared<LevelFormatItem>();
            if (key == "c")
                return std::make_shared<NameFormatItem>();
            if (key == "f")
                return std::make_shared<CFileFormatItem>();
            if (key == "l")
                return std::make_shared<CLineFormatItem>();
            if (key == "m")
                return std::make_shared<MsgFormatItem>();
            if (key == "T")
                return std::make_shared<TabFormatItem>();
            if (key == "n")
                return std::make_shared<NLineFormatItem>();
            if (value.empty() == false)
                return std::make_shared<OtherFormatItem>(value);
            return FormatItem::ptr();
        }

    private:
        std::string _pattern;                // 记录当前日志消息格式
        std::vector<FormatItem::ptr> _items; // 存储的是格式项基类句柄（shared_ptr）
    };
}

#endif